package com.code.file;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 * 文件操作类
 * @author liyufei
 * @since 2018-11-28 11:07 AM
 */
public class FileUtils {

    /**
     * 删除文件或文件夹（若文件夹下面有文件，会先删除文件夹下面所有内容，在删除文件夹）
     * @param file
     */
    public static void delete(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File key : files) {
                if (key.isFile()) {
                    key.delete();
                } else {
                    delete(key);
                }
            }
        }
        file.delete();
    }

    /**
     * 读取指定路径的文件内容，写入到内存中，这里即字符串String
     * @param path
     */
    public static String loadToString(String path) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(new File(path));
             StringWriter writer = new StringWriter()
        ) {
            IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
            return writer.toString();
        }
    }
}
